var AppointmentDateTimeChanged = false;
var prevSlider = "";
var allowTimes = "";
$(document).ready(function () {
    if ($("#product_search").val() == "" || $("#apptDate").val() == "") {
        $("#btnSave,#btnDelete,#completeAppt").attr('disabled', 'disabled');
    }
    $('input[type=file]').bootstrapFileInput();
    $('.file-inputs').bootstrapFileInput();
    $("#btnSavePrescription").attr('disabled', 'disabled');
    //$('#upload').change(
    //function (e) {
    //    $('#selectedFileList').empty();
    //    var numFiles = e.currentTarget.files.length;
    //    for (i = 0; i < numFiles; i++) {
    //        var liObj = $('<li />');
    //        //if (e.currentTarget.files && e.currentTarget.files[0]) {
    //            var reader = new FileReader();

    //            reader.onload = function (e1) {
    //                liObj.append($("<img/>").attr('src', e1.target.result));
    //            }

    //            reader.readAsDataURL(e.currentTarget.files[0]);
    //        //}
    //            liObj.append($("<span/>").html(e.currentTarget.files[i].name));
    //            liObj.appendTo($('#selectedFileList'));
    
    //    }
    //});
    $('#upload').change(
    function (e) {
        $('#selectedFileList').empty();
        var numFiles = e.currentTarget.files.length;
        for (i = 0; i < numFiles; i++) {
            var liObj = $('<li />');
            liObj.append($("<span/>").html(e.currentTarget.files[i].name));
            liObj.appendTo($('#selectedFileList'));
        }
    });



    $("#product_search").keyup(function () {
        if ($("#product_search").val() != "" && $("#apptDate").val() != "") {
            $("#btnSave,#btnDelete,#completeAppt").removeAttr('disabled');
        } else {
            $("#btnSave,#btnDelete,#completeAppt").attr('disabled', 'disabled');
            $("#bookDetailPhone,#bookDetailPurpose,#emailId,#patientDetailPhone,#patientAllergies").val("");

            $("#lastApptPanel").css("display", "none");
            $(".bx-wrapper").html("");
            $("#divVisitDetails").css("display", "none");
        }
        appointmentDoctorObject.Patient.Id = 0;
        appointmentDoctorObject.Id = 0;
    });

    $("#apptDate").keyup(function () {
        if ($("#product_search").val() != "" && $("#apptDate").val() != "") {
            $("#btnSave,#btnDelete,#completeAppt").removeAttr('disabled');

        } else {
            $("#btnSave,#btnDelete,#completeAppt").attr('disabled', 'disabled');
        }
    });
    
    $('input:checkbox').bootstrapSwitch();
    $("#slotTiming").combobox();
    $("#dateOfBirth").change(function () {
        var dateOfBirth = $(this).val().split('/');
        var dobYear = dateOfBirth.length ? new Date(dateOfBirth[2], dateOfBirth[1] - 1, dateOfBirth[0]).getYear() : new Date();
        var currentYear = new Date().getYear();
        $("#age").val(((currentYear - dobYear) >= 0 ? currentYear - dobYear : 0) + 'yr');
    });
    $("#dateOfBirth").trigger("change");
    var DocInfo = JSON.parse(localStorage.getItem("DoctorInfo"));
    if (DocInfo && DocInfo.DocId) {
        setDoctorSlots(DocInfo.DocId);
    }
    if (!(isAnynomous || userType == 'patient'))
        $('#product_search').typeahead({
            source: function (query, process) {
                var $items = new Array;
                $items = [""];
                $.ajax({
                    type: "POST",
                    url: _AbsolutePath + 'Patient/GetPatientName',
                    contentType: "application/json",
                    data: JSON.stringify({ PatientName: query }),
                    dataType: "json",
                    success: function (data) {

                        $("input").not("#product_search").val(undefined);
                        var selectedDate = localStorage.getItem("selectedDate");
                        if (selectedDate) {
                            selectedDate = selectedDate.split(',');
                            $("#apptDate").val(new Date(selectedDate[0], selectedDate[1], selectedDate[2], allowTimes[0].split(':')[0], allowTimes[0].split(':')[1]).toString("dd/MM/yyyy (hh:mm:tt)"));
                        }
                        else {
                            $("#apptDate").val(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), allowTimes[0].split(':')[0], allowTimes[0].split(':')[1]).toString("dd/MM/yyyy (hh:mm:tt)"));
                        }
                        $('#chkFollowup,#chkGender').bootstrapSwitch('state', false, true);

                        $.map(data, function (data) {
                            var group;
                            var phone = data.Phone != "" && data.Phone != null ? data.Phone : "";
                            var email = data.Email != "" && data.Email != null ? data.Email : "";
                            group = {
                                id: data.Id,
                                name: data.Name + " ( " + phone + ", " + email + " ) ",
                                toString: function () {
                                    return JSON.stringify(this);
                                    //return this.app;
                                },
                                toLowerCase: function () {
                                    return this.name.toLowerCase();
                                },
                                indexOf: function (string) {
                                    return String.prototype.indexOf.apply(this.name, arguments);
                                },
                                replace: function (string) {
                                    var value = '';
                                    value += this.name;
                                    if (typeof (this.level) != 'undefined') {
                                        value += ' <span class="pull-right muted">';
                                        value += this.level;
                                        value += '</span>';
                                    }
                                    return value;
                                }
                            };
                            $items.push(group);
                        });

                        process($items);
                    }
                });
            },
            property: 'name',
            items: 10,
            minLength: 1,
            updater: function (item) {
                var item = JSON.parse(item);

                $('#SelectedPatient').val(item.id);
                GetPatientInfo(item.id);
                return item.name;
            }
        });
    //$('.datepicker').datepicker();
    $(".combobox-container input[type='text']").attr("placeholder", "Select slot").attr("style", "width:150px");
    $("#btnSave").click(function () {
        var DocInfo = JSON.parse(localStorage.getItem("DoctorInfo"));
        appointmentDoctorObject.DocId = parseInt(DocInfo.DocId);
        appointmentDoctorObject.LocId = parseInt(DocInfo.LocId);
        if (!appointmentDoctorObject.Id) {
            appointmentDoctorObject.AppointmentStatus = { Id: 2 };
            //appointmentDoctorObject.CreatedDate = new Date();
            appointmentDoctorObject.ModifiedDate = new Date();
            //if (!appointmentDoctorObject.AppointmentDateTime) {
            var datetime = $("#apptDate").val().replace('(', '').replace(')', '').split(' ');
            appointmentDoctorObject.AppointmentDateTime = new Date(datetime[0].split('/')[2], datetime[0].split('/')[1] - 1, datetime[0].split('/')[0], datetime[1].split(':')[2] == "AM" ? datetime[1].split(':')[0] : parseInt(datetime[1].split(':')[0]) + 12, datetime[1].split(':')[1]);
            if (environment == "prod")
                var _apptDT = $("#apptDate").val().replace('(', '').replace(')', '').split('/')[1] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[0] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[2];
            else
                var _apptDT = $("#apptDate").val().replace('(', '').replace(')', '').split('/')[0] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[1] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[2];
            appointmentDoctorObject._AppointmentDateTime = _apptDT.substring(0, 16) + " " + _apptDT.substring(17, 19);
        }
        else {
            //appointmentDoctorObject.CreatedDate = (new Date(parseInt(appointmentDoctorObject.CreatedDate.replace("/Date(", "").replace(")/", ""))));
            appointmentDoctorObject.ModifiedDate = (new Date(parseInt(appointmentDoctorObject.ModifiedDate.replace("/Date(", "").replace(")/", ""))));
            if (environment == "prod")
                var _apptDT = $("#apptDate").val().replace('(', '').replace(')', '').split('/')[1] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[0] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[2];
            else
                var _apptDT = $("#apptDate").val().replace('(', '').replace(')', '').split('/')[0] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[1] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[2];
            appointmentDoctorObject._AppointmentDateTime = _apptDT.substring(0, 16) + " " + _apptDT.substring(17, 19);
            if (!AppointmentDateTimeChanged)
                appointmentDoctorObject.AppointmentDateTime = (new Date(parseInt(appointmentDoctorObject.AppointmentDateTime.replace("/Date(", "").replace(")/", ""))));
        }
        var patientName = $("#product_search").val();
        appointmentDoctorObject.Patient.Name = patientName.substring(0, patientName.indexOf('(') > 0 ? (patientName.indexOf('(') - 1) : patientName.length);
        appointmentDoctorObject.Patient.Phone = $("#bookDetailPhone").val() != null ? $("#bookDetailPhone").val() : $("#patientDetailPhone").val();
        appointmentDoctorObject.FollowUpStatus = $("#chkFollowup:checked").length > 0 ? true : false;
        appointmentDoctorObject.Purpose = $("#bookDetailPurpose").val();
        appointmentDoctorObject.Patient.Email = $("#emailId").val();
        appointmentDoctorObject.Patient.Phone = $("#bookDetailPhone").val();
        appointmentDoctorObject.Patient.Allergies = $("#patientAllergies").val();
        if ($("#dateOfBirth").val()) {
            var dateOfBirth = $("#dateOfBirth").val().split('/');
            appointmentDoctorObject.Patient.DOB = new Date(dateOfBirth[2], dateOfBirth[1] - 1, dateOfBirth[0]);
        }
        else {
            appointmentDoctorObject.Patient.DOB = new Date();
        }
        //appointmentDoctorObject.ApptDate = convertStringToDate($("#apptDate").val());
        //appointmentDoctorObject.ApptTime = $("#slotTiming").val();
        // if (!appointmentDoctorObject.Gender) appointmentDoctorObject.Gender = {};
        appointmentDoctorObject.Patient.Gender.Id = $("#chkGender:checked").length > 0 ? 1 : 2;


        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/SaveAppointmentDetails',
            contentType: "application/json",
            data: JSON.stringify({ doctorAppointmentResponse: appointmentDoctorObject }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                if (res.ErrorMessage != null && res.ErrorMessage != "") {
                    alert(res.ErrorMessage);
                }
                else if (res.Id > 0) {
                    alert("Appointment saved succesfully");
                    if (res.isNew == true) {
                        sendEmail(res);
                    } else {
                        sendEmailforCompletedApp(res.Id);
                    }
                    var datetime = $("#apptDate").val().replace('(', '').replace(')', '').split(' ');
                    if (isAnynomous) {
                        alert("Please keep a note that your access code to login will be " + res.AccessCode);
                        $.ajax({
                            type: "POST",
                            url: _AbsolutePath + 'User/ValidateUser',
                            contentType: "application/json",
                            data: JSON.stringify({ accessCode: res.AccessCode }),
                            caller: arguments.callee.name,//gets currently running function name
                            dataType: "json", //Cross domain call (even json also work)
                            success: function (res) {
                                if (res.Id > 0) {
                                    if (res.Detail === "D")
                                        location.href = "/Appointment/AppoinmentIndex";
                                    else
                                        location.href = "/Patient/Index";
                                }
                                else {
                                    $("#loginError").removeClass("hide");
                                }
                            },
                            error: function (xhr) { debugger; }
                        });
                    }
                    else if (userType == 'patient') {
                        location.href = "/patient";
                    }
                    else {
                        var _date = "";
                        if (environment == "prod") {
                            _date = datetime[0].split('/')[1] + "/" + datetime[0].split('/')[0] + "/" + datetime[0].split('/')[2];
                        } else {
                            _date = datetime[0].split('/')[0] + "/" + datetime[0].split('/')[1] + "/" + datetime[0].split('/')[2];
                        }
                        LoadApptDetails(_date);
                    }

                }
                else {
                    alert("Appointment not saved");
                    if (res.AppointmentStatus != null && res.AppointmentStatus.Id == 2) {
                        $("#completeAppt").css("display", "block");
                        $("#btnDelete").css("display", "block");
                    }
                    else {
                        $("#completeAppt").css("display", "none");
                        $("#btnDelete").css("display", "none");
                    }
                }
            },
            error: function (xhr) {
                //alert(1);
                //location.href = "/Appointment/AppointmentDetails
            }
        });
    });

    $("#completeAppt").click(function () {
        if (confirm("Do you want to complete this appointment?")) {
            var DocInfo = JSON.parse(localStorage.getItem("DoctorInfo"));
            appointmentDoctorObject.DocId = parseInt(DocInfo.DocId);
            appointmentDoctorObject.LocId = parseInt(DocInfo.LocId);
            appointmentDoctorObject.CreatedDate = (new Date(parseInt(appointmentDoctorObject.CreatedDate.replace("/Date(", "").replace(")/", ""))));
            appointmentDoctorObject.ModifiedDate = (new Date(parseInt(appointmentDoctorObject.ModifiedDate.replace("/Date(", "").replace(")/", ""))));
            appointmentDoctorObject.AppointmentDateTime = (new Date(parseInt(appointmentDoctorObject.AppointmentDateTime.replace("/Date(", "").replace(")/", ""))));
            if (environment == "prod")
                var _apptDT = $("#apptDate").val().replace('(', '').replace(')', '').split('/')[1] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[0] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[2];
            else
                var _apptDT = $("#apptDate").val().replace('(', '').replace(')', '').split('/')[0] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[1] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[2];
            appointmentDoctorObject._AppointmentDateTime = _apptDT.substring(0, 16) + " " + _apptDT.substring(17, 19);
            appointmentDoctorObject.AppointmentStatus = { Id: 3 };
            appointmentDoctorObject.Patient.DOB = (new Date(parseInt(appointmentDoctorObject.Patient.DOB.replace("/Date(", "").replace(")/", ""))));
            $.ajax({
                type: "POST",
                url: _AbsolutePath + 'Appointment/SaveAppointmentDetails',
                contentType: "application/json",
                data: JSON.stringify({ doctorAppointmentResponse: appointmentDoctorObject }),
                caller: arguments.callee.name,//gets currently running function name
                dataType: "json", //Cross domain call (even json also work)
                success: function (res) {
                    if (res.Id > 0) {
                        sendEmailforCompletedApp(_appointmentId);
                        alert("Appointment completed succesfully");
                        var datetime = $("#apptDate").val().replace('(', '').replace(')', '').split(' ');
                        var _date = '';
                        if (environment == "prod") {
                            _date = datetime[0].split('/')[1] + "/" + datetime[0].split('/')[0] + "/" + datetime[0].split('/')[2];
                        } else {
                            _date = datetime[0].split('/')[0] + "/" + datetime[0].split('/')[1] + "/" + datetime[0].split('/')[2];
                        }

                        LoadApptDetails(_date);
                    }
                    else {
                        alert("Appointment not completed");
                    }
                },
                error: function (xhr) {
                    alert("Appointment not completed");
                }
            });
        }
    });


    $("#btnDelete").click(function () {
        if (confirm("Do you want to delete this appointment?")) {
            $.ajax({
                type: "POST",
                url: _AbsolutePath + 'Appointment/DeleteAppointment',
                contentType: "application/json",
                data: JSON.stringify({ DocAppId: _appointmentId }),
                caller: arguments.callee.name,//gets currently running function name
                dataType: "json", //Cross domain call (even json also work)
                success: function (res) {
                    sendEmailforDeleteApp(res);
                    alert("Appointment deleted succesfully");
                    location.href = "/Appointment/AppointmentDetail"
                },
                error: function (xhr) {
                    alert(1);
                }
            });
        }
    });


    $.ajax({
        type: "POST",
        url: _AbsolutePath + '/Appointment/GetLocationList',
        contentType: "application/json",
        data: JSON.stringify({ clinicCode: localStorage.getItem("ClinicCode") }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            $('#location').empty();
            if (res.length > 1)
                $('#location').append($('<option id=""\/>').val('').text('(Select Location)'));
            for (var i = 0; i < res.length; i++) {
                $('#location').append($('<option id="' + res[i].Id + '"\/>').val(res[i].Id).text(res[i].Detail));
            }
            if (res.length == 1) {
                $('#location option#' + res[0].Id).prop("selected", true);
                $('#location').trigger("change");
            }
        },
        error: function (xhr) { debugger; }
    });
    $("#location").on("change", function () {
        $('#doctors').val('').attr('selected', true);
        // $('#doctors').trigger("change");
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/GetDoctorList',
            contentType: "application/json",
            data: JSON.stringify({ LocId: $("#location").val() }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                $('#doctors').empty();
                if (res.length > 1)
                    $('#doctors').append($('<option id=""\/>').val('').text('(Select Doctor)'));
                for (var i = 0; i < res.length; i++) {
                    $('#doctors').append($('<option id="' + res[i].Id + '"\/>').val(res[i].Id).text(res[i].Detail));
                }
                if (res.length == 1) {
                    $('#doctors option#' + res[0].Id).prop("selected", true);
                    $('#doctors').trigger("change");
                }
            },
            error: function (xhr) { debugger; }
        });
    });
    $("#doctors").on("change", function () {
        $("#doctorName").html('');
        localStorage.setItem("DoctorInfo", JSON.stringify({ DocId: $(this).val(), LocId: $("#location").val() }));
        if ($("#doctors option:selected").val()) {
            $("#doctorName").html("(" + $("#doctors option:selected").html() + ")");
            $(".edit-appointment > .bs-example").css("display", "block");
            setDoctorSlots($(this).val());
        }
        else { $(".edit-appointment > .bs-example").css("display", "none"); }
    });

    GetImageList(_appointmentId);
    GetPrevApptImageList();
    $("#txtPrescription").keyup(function () {
        if ($("#txtPrescription").val() == "")
            $("#btnSavePrescription").attr('disabled', 'disabled');
        else
            $("#btnSavePrescription").removeAttr('disabled');
    });

    $("#btnSavePrescription").click(function () {
        var request = {};
        request.Prescription = $("#txtPrescription").val();
        $.ajax({
            type: "POST",
            url: _AbsolutePath + '/Appointment/SavePrescriptionText',
            contentType: "application/json",
            data: JSON.stringify({ appDoc: request }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {

                var count = $("#divPrescription .label-info").length + 1;
                GeneratePresciptionDiv($("#txtPrescription").val(), new Date().toString("dd/MM/yyyy hh:mm tt"), "divPrescription", count);
                $("#txtPrescription").val("");
                sendEmailforCompletedApp(res);

            },
            error: function (xhr) { debugger; }
        });
    });
});

function GetPatientInfo(PatId) {
    var _date = "";
    if (environment == "prod") {
        _date = $("#apptDate").val().split(" ")[0].split('/')[1] + "/" + $("#apptDate").val().split(" ")[0].split('/')[0] + "/" + $("#apptDate").val().split(" ")[0].split('/')[2];
    } else {
        _date = $("#apptDate").val().split(" ")[0];
    }
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Patient/GetPatientById',
        contentType: "application/json",
        data: JSON.stringify({ PatientId: PatId,date:_date}),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            if (res != null) {
                if (res._AppointmentDateTime != "" && res._AppointmentDateTime != null && res._AppointmentDateTime != "01/01/0001 (12:00:AM)") {
                    $("#lastApptPanel").removeAttr("style");
                }
                $("#bookDetailPhone").val(res.Patient.Phone);
                //if(res.Patient.Phone)
                //    $("#lastApptPanel").css("display","none");
                $("#lastApptPurpose").html(res.Purpose);
                $("#lastApptDet").html(res._AppointmentDateTime);

                if (res.FollowUpStatus == true)
                    $("#chkFollowup").bootstrapSwitch('state', true, true);
                else
                    $("#chkFollowup").bootstrapSwitch('state', false, false);
                $("#emailId").val(res.Patient.Email);
                $("#patientDetailPhone").val(res.Patient.Phone);
                $("#age").val((new Date(parseInt(res.Patient.DOB.replace("/Date(", "").replace(")/", "")))).getDate().toString());
                if (res.Patient.Gender.Id == 1)
                    $('#chkGender').bootstrapSwitch('state', true, true);
                else
                    $('#chkGender').bootstrapSwitch('state', false, false);
                $("#newDocApptId").val(res.Id);
                appointmentDoctorObject = res
                appointmentDoctorObject.Id = $("#DocApptId").val();
                GetImageList(res.Id);
                //  if (res.Patient.Gender.Id == 1) $("#chkGender").prop('checked', true);
            }
        },
        error: function (xhr) {
        }
    });
}

function LoadApptDetails(_date1) {
    var DocInfo = JSON.parse(localStorage.getItem("DoctorInfo"));
    $.ajax({
        type: "POST",
        url: _AbsolutePath + 'Appointment/AddDoctorDetails',
        contentType: "application/json",
        data: JSON.stringify({ DocId: parseInt(DocInfo.DocId), LocId: parseInt(DocInfo.LocId), date: _date1 }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            SelectedDate = _date1;
            location.href = _AbsolutePath + "Appointment/AppointmentDetail";
        },
        error: function (xhr) {

        }
    });
}

function GetImageList(ApptId) {
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Appointment/GetImageList',
        contentType: "application/json",
        data: JSON.stringify({ DocApptId: ApptId }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            if (res != null && res.length > 0) {
                var isImageGenerated = false;
                for (var i = 0; i < res.length; i++) {
                    if (res[i].ImagePath != null && res[i].ImagePath != "") {
                        if (res[i].isImage == true) {
                            $("#addedImages").append("<li styl='width:100'><a class='fancybox'  rel='group' href=" + res[i].ImagePath + "><img src=" + res[i].ThumbnailPath + " alt='' /></a></li>");
                        } else {
                            $("#addedImages").append("<li styl='width:100'><a class='fancybox'  rel='group' href=" + res[i].ImagePath + "><img src=" + _AbsolutePath +"/"+ res[i].ThumbnailPath + " class='fa fa-file-word-o' /></a></li>");
                        }
                        isImageGenerated = true;
                    } else {
                        GeneratePresciptionDiv(res[i].Prescription, res[i]._PrescriptionTime, "divPrescription", i);
                    }
                }
                if (isImageGenerated == true) {
                    $(".fancybox").fancybox();
                    $("#addedImages").bxSlider({
                        minSlides: 2,
                        maxSlides: 10,
                        slideWidth: 250,
                        slideMargin: 5,
                        infiniteLoop: true
                    });
                }
            }
        },
        error: function (xhr) {
        }
    });
}

function sendEmail(appointmentDoctorObject) {
    appointmentDoctorObject.AppointmentDateTime = (new Date(parseInt(appointmentDoctorObject.AppointmentDateTime.replace("/Date(", "").replace(")/", ""))));
    var _apptDT = $("#apptDate").val().replace('(', '').replace(')', '').split('/')[1] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[0] + "/" + $("#apptDate").val().replace('(', '').replace(')', '').split('/')[2];
    appointmentDoctorObject._AppointmentDateTime = _apptDT.substring(0, 16) + " " + _apptDT.substring(17, 19);
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Appointment/SendEmailforAppointmentBooked',
        contentType: "application/json",
        data: JSON.stringify({ SavedData: appointmentDoctorObject }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {

        },
        error: function (xhr) {
        }
    });
}

function setDoctorSlots(docID) {
    $.ajax({
        type: "POST",
        url: _AbsolutePath + 'Appointment/GetDoctorSlots',
        contentType: "application/json",
        data: JSON.stringify({ DocId: parseInt(docID) }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            allowTimes = [
              '08:00', '08:30', '09:00', '09:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00', '15:30', '16:00', '16:30', '17:00',
               '17:30', '18:00', '18:30', '19:00', '19:30', '20:00'
            ];
            _.each(res, function (item) {
                allowTimes = _.without(allowTimes, item);
            });
            $("#apptDate").removeAttr("disabled");
            setAppointmentDateTimeCallender(allowTimes);
        },
        error: function (xhr) {
            //alert(1);
            //location.href = "/Appointment/AppointmentDetails
        }
    });

}

function SetDayOff(date) {
    var DocInfo = JSON.parse(localStorage.getItem("DoctorInfo"));
    $.ajax({
        type: "POST",
        url: _AbsolutePath + 'Appointment/DoctorsDayOff',
        contentType: "application/json",
        data: JSON.stringify({ DocId: parseInt(DocInfo.DocId), Year: date.getFullYear(), Month: date.getMonth() + 1 }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {
            //$(callenderObj).find('.xdsoft_time_variant .xdsoft_current').removeClass("xdsoft_current");
            //$.each(res, function (index, item) {
            //item
            $.each(res, function (index, item) {
                //item
                $(".xdsoft_calendar tbody tr td[data-date=" + parseInt(item.split("/")[0]) + "]").each(function (index, item2) {
                    if (parseInt($(item2).attr("data-month")) == parseInt(item.split("/")[1]) - 1) {
                        $(item2).addClass("xdsoft_disabled")
                    }
                })
                ///$($(".xdsoft_calendar tbody tr td[data-date=" + item.split("/")[1] + "]")[0]).addClass("xdsoft_disabled")
            });
        },
        error: function (xhr) {
            //alert(1);
            //location.href = "/Appointment/AppointmentDetails
        }
    });
}

function setAppointmentDateTimeCallender(allowTimes) {
    $('.datetimepicker').datetimepicker({
        onChangeDateTime: function (dp, $input) {
            //var datetime = $input.val().replace('(', '').replace(')', '').split(' ');
            appointmentDoctorObject.AppointmentDateTime = new Date(dp.getFullYear(), dp.getMonth(), dp.getDate(), dp.getHours(), dp.getMinutes());
            AppointmentDateTimeChanged = true;
        },
        allowTimes: allowTimes,
        onShow: function (current_time, $input) {
            //if (!AppointmentDateTimeChanged) {

            $(".xdsoft_datetimepicker > div:first-child > .note-bit").remove();
            $(".xdsoft_datetimepicker > div:first-child").append('<div class="note-bit">The busy time slots are highlighted in blue.</div>');
            SetBusyTimeSlots(new Date(current_time.getFullYear(), current_time.getMonth(), current_time.getDate()), $input, this);
            SetDayOff(current_time);
            //}
            //return false;
        },
        format: 'd/m/Y (h:i:A)',
        formatDate: 'd.m.Y',
        formatTime: 'h:i',
        validateOnBlur: false,
        defaultDate: function () {
            var selectedDate = localStorage.getItem("selectedDate");
            if (localStorage.getItem("selectedDate")) {
                selectedDate = selectedDate.split(',');
                return new Date(selectedDate[0], selectedDate[1], selectedDate[2])
            }
            else {
                return new Date()
            }
        }(),
        onChangeMonth: function (current_time) {
            SetDayOff(current_time);
        },
        value: function () {
            if (!parseInt(_appointmentId)) {
                var selectedDate = localStorage.getItem("selectedDate");
                if (localStorage.getItem("selectedDate")) {
                    selectedDate = selectedDate.split(',');
                    return new Date(selectedDate[0], selectedDate[1], selectedDate[2], allowTimes[0].split(':')[0], allowTimes[0].split(':')[1]).toString("dd/MM/yyyy (hh:mm:tt)");
                }
                else {
                    return new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), allowTimes[0].split(':')[0], allowTimes[0].split(':')[1]).toString("dd/MM/yyyy (hh:mm:tt)");
                }
            }
        }(),

        onSelectDate: function (current_time, $input) {
            SetBusyTimeSlots(current_time, $input, this);
            AppointmentDateTimeChanged = false;

        }
    });

    $("#apptDate").keydown(false);
}

function SetBusyTimeSlots(current_time, $input, callenderObj) {
    var DocInfo = JSON.parse(localStorage.getItem("DoctorInfo"));
    if (DocInfo) {
        //var callenderObj = this;
        $input.val(new Date(current_time.getFullYear(), current_time.getMonth(), current_time.getDate(), allowTimes[0].split(':')[0], allowTimes[0].split(':')[1]).toString("dd/MM/yyyy (hh:mm:tt)"));
        $.ajax({
            type: "POST",
            url: _AbsolutePath + 'Appointment/GetDayAppointmentList',
            contentType: "application/json",
            data: JSON.stringify({ DocId: parseInt(DocInfo.DocId), LocId: parseInt(DocInfo.LocId), date: environment == "prod" ? current_time.toString("MM/dd/yyyy") : current_time.toString("dd/MM/yyyy") }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                $(callenderObj).find('.xdsoft_time_variant .xdsoft_current').removeClass("xdsoft_current");
                $.each(res, function (index, item) {
                    var hour = parseInt(item._ApptTime.split(':')[0]).toString();
                    var minute = item._ApptTime.split(':')[1];
                    if (minute == "00") minute = 0;
                    $('.xdsoft_time_variant').find(".xdsoft_time[data-hour=" + hour + "][data-minute=" + minute + "]").addClass("xdsoft_current");
                });
            },
            error: function (xhr) {
                //alert(1);
                //location.href = "/Appointment/AppointmentDetails
            }
        });
    }
}

function GetPrevApptImageList() {
    if (prevAppointment != null) {
        $.ajax({
            async: true,
            type: "POST",
            url: _AbsolutePath + 'Appointment/GetImageList',
            contentType: "application/json",
            data: JSON.stringify({ DocApptId: prevAppointment.Id }),
            caller: arguments.callee.name,//gets currently running function name
            dataType: "json", //Cross domain call (even json also work)
            success: function (res) {
                if (res != null && res.length > 0) {
                    var isImageGenerated = false;
                    for (var i = 0; i < res.length; i++) {
                        if (res[i].ImagePath != null && res[i].ImagePath != "") {
                            $("#prevAppt_" + prevAppointment.Id).append("<li styl='width:100'><a class='fancybox'  rel='group' href=" + res[i].ImagePath + "><img src=" + res[i].ThumbnailPath + " alt='' /></a></li>");
                            isImageGenerated = true;
                        } else {
                            GeneratePresciptionDiv(res[i].Prescription, res[i]._PrescriptionTime, "divPrevPrescription", i);
                        }
                    }
                    if (isImageGenerated == true) {
                        $("#prevAppt_" + prevAppointment.Id + ".fancybox").fancybox();
                        prevSlider = $("#prevAppt_" + prevAppointment.Id).bxSlider({
                            minSlides: 2,
                            maxSlides: 10,
                            slideWidth: 250,
                            slideMargin: 5,
                            infiniteLoop: true
                        });
                    }
                }
            },
            error: function (xhr) {
            }
        });
    }
}

function sendEmailforDeleteApp(DocApptId) {
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Appointment/SendEmailforAppointmentDeleted',
        contentType: "application/json",
        data: JSON.stringify({ docAppt: DocApptId }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {

        },
        error: function (xhr) {
        }
    });
}

function sendEmailforCompletedApp(DocApptId) {
    $.ajax({
        async: true,
        type: "POST",
        url: _AbsolutePath + 'Appointment/SendEmailforAppointmentCompleted',
        contentType: "application/json",
        data: JSON.stringify({ docApptId: DocApptId }),
        caller: arguments.callee.name,//gets currently running function name
        dataType: "json", //Cross domain call (even json also work)
        success: function (res) {

        },
        error: function (xhr) {
        }
    });
}
